#ifndef THREAD_H_
#define THREAD_H_

#include <pthread.h>

#include <functional>
#include <string>

#include "netlib/base/atomic.h"
#include "netlib/base/count_down_latch.h"
#include "netlib/base/noncopyable.h"

namespace netlib {

class Thread : NonCopyable {
public:
	using ThreadFunc = std::function<void()>;

	explicit Thread(ThreadFunc func, const std::string& name = "");
	~Thread();

	void Start();
	int Join();

	bool Started() const { return is_started_; }
	pid_t Tid() const { return tid_; }
	std::string Name() const { return name_; }

	static int CreateNum() { return num_created.Get(); }

private:
	bool is_started_{false};
	bool is_joined_{false};
	pid_t tid_{0};
	pthread_t pthread_{0};
	ThreadFunc func_;
	std::string name_;
	CountDownLatch latch_{1};

	static AtomicInt32 num_created;
};

} // namespace netlib

#endif // THREAD_H_